import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_todolist/db/db.dart';
import 'package:flutter_todolist/db/table/user_table.dart';
import 'package:flutter_todolist/pages/auth/widget/auth_input.dart';
import 'package:flutter_todolist/utils/auth.dart';
import 'package:flutter_todolist/utils/extention.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';
import '../../util.dart';
import '../../utils/common.dart';
import '../../widgets/app_button.dart';
import 'auth_login.dart';


class AuthRegister extends StatefulWidget {
  const AuthRegister({Key? key}) : super(key: key);

  @override
  State<AuthRegister> createState() => _AuthRegisterState();
}

class _AuthRegisterState extends State<AuthRegister> {
  final regCtrl = Get.put(AuthRegisterController());

  // TextEditingController accountCtrl = TextEditingController();
  // TextEditingController codeCtrl = TextEditingController();

  // SmsController smsController = SmsController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          Container(
            margin: EdgeInsets.symmetric(horizontal: 30.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                120.h.hSizedBox(),
                top(),
                20.h.hSizedBox(),
                // tabs(),
                // 20.h.hSizedBox(),
                Expanded(child: register())
              ],
            ),
          ),
          Positioned(
            left: 15.w,
            top: 30.h,
            child: GestureDetector(
              onTap: () {
                Get.back();
              },
              child: Icon(Icons.arrow_back_ios_rounded, size: 30.r),
            )
          )
        ],
      ),
    );
  }

  Widget top() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          child: Center(
            child: 'Clipboard'.assetsImg(width: 120.r, height: 120.r, fit: BoxFit.cover),
          ),
        ),
        20.h.hSizedBox(),
        '注册'.text(fontSize: 28),
      ],
    );
  }

  Widget register() {
    return Column(
      children: [
        AuthInput(
          prefix: '@'.text(fontSize: 20.sp, color: Color(0xFF85888c)),
          hintText: 'enter account',
          controller: regCtrl.accountCtrl,
          inputFormatter: [
            LengthLimitingTextInputFormatter(11),
            FilteringTextInputFormatter.digitsOnly
          ],
        ),
        // 10.h.hSizedBox(),
        // Row(
        //   children: [
        //     Expanded(child: AuthInput(
        //       prefix: FaIcon(FontAwesomeIcons.message, size: 18.r, color: Color(0xFF85888c)),
        //       hintText: 'enter code',
        //       controller: codeCtrl,
        //       inputFormatter: [
        //         LengthLimitingTextInputFormatter(6),
        //         FilteringTextInputFormatter.digitsOnly
        //       ],
        //     )),
        //     10.h.hSizedBox(),
        //     // Container(
        //     //   width: 80.w,
        //     //   alignment: Alignment.center,
        //     //   child: SmsCode(
        //     //     initText: '发送验证码',
        //     //     controller: smsController,
        //     //     completeText: '重新发送',
        //     //   ).onPress((){
        //     //     regCtrl.sendSms();
        //     //   }),
        //     // )
        //   ],
        // ),
        10.h.hSizedBox(),
        Obx(() => AuthInput(
          prefix: FaIcon(FontAwesomeIcons.lock, color: Color(0xFF85888c), size: 18.r),
          hintText: 'enter password',
          controller: regCtrl.passwordCtrl,
          suffix: GestureDetector(
            onTap: () {
              regCtrl.passwordSwitch();
            },
            child: FaIcon(
                regCtrl.passwordSecure.value == true
                    ? FontAwesomeIcons.eyeSlash : FontAwesomeIcons.eye ,
                color: Color(0xFF85888c), size: 18.r),
          ),
          obscureText: regCtrl.passwordSecure.value,
        )),
        10.h.hSizedBox(),
        Obx(() => AuthInput(
          prefix: FaIcon(FontAwesomeIcons.lock, color: Color(0xFF85888c), size: 18.r),
          hintText: 'confirm password',
          controller: regCtrl.passwordConfirmCtrl,
          suffix: GestureDetector(
            onTap: () {
              regCtrl.passwordConfirmSwitch();
            },
            child: FaIcon(
                regCtrl.passwordConfirmSecure.value == true
                    ? FontAwesomeIcons.eyeSlash : FontAwesomeIcons.eye ,
                color: Color(0xFF85888c), size: 18.r),
          ),
          obscureText: regCtrl.passwordConfirmSecure.value,
        )),
        50.h.hSizedBox(),
        AppButton(
          height: 40.h,
          content: '注册',
          gradientColors: const [
            CustomColors.PurpleDark,
            CustomColors.PurpleAccent,
          ],
          onTap: () {
            regCtrl.register();
            // Get.to(() => AuthSetPasswordPage());
            // regCtrl.reg();
          },
        )
      ],
    );
  }

}


class AuthRegisterController extends GetxController {
  var passwordSecure = true.obs;
  var passwordConfirmSecure = true.obs;

  TextEditingController accountCtrl = TextEditingController();
  // TextEditingController codeCtrl = TextEditingController();
  TextEditingController passwordCtrl = TextEditingController();
  TextEditingController passwordConfirmCtrl = TextEditingController();

  late UserTable userTable;

  @override
  void onInit() {
    userTable = ToDoDB().userTable;
    super.onInit();
  }

  void passwordSwitch() {
    passwordSecure.value = !passwordSecure.value;
  }

  void passwordConfirmSwitch() {
    passwordConfirmSecure.value = !passwordConfirmSecure.value;
  }

  void setPassword() {

  }

  bool checkPassword() {
    if (accountCtrl.text.isEmpty) {
      showToast('账号不能为空');
      return false;
    }

    if (passwordCtrl.text.isEmpty) {
      showToast('密码不能为空');
      return false;
    }

    if (passwordConfirmCtrl.text.isEmpty) {
      showToast('确认密码不能为空');
      return false;
    }

    if (passwordCtrl.text != passwordConfirmCtrl.text) {
      showToast('两次输入密码不一致');
      return false;
    }

    return true;
  }

  register() async {
    if (checkPassword()) {

      List<Map> dbAccounts = await userTable.queryList(
          where: "account = ?",
          whereArgs: [accountCtrl.text]
      );

      if (dbAccounts.isEmpty) {
        User newUser = User(
            userId: generateRandomString(10),
            name: "",
            avatar: "",
            age: 18,
            gender: 0,
            account: accountCtrl.text,
            password: passwordCtrl.text
        );
        try {
          await userTable.insertItem(newUser.toJson());
          showToast('注册成功, 自动为您登录');
          Auth.login(newUser);
        } on Exception catch (e) {
          debugPrint("error: ${e.toString()}");
        }
      } else {
        showToast('该账号已经注册');
      }


    }
  }

}
